package fan.com.httpframe.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;

import java.lang.reflect.Field;

import fan.com.httpframe.R;
import fan.com.httpframe.imageloder.ImageLoader;
import fan.com.httpframe.view.loading.LoadingHandler;

/**
 * 文件名：
 * 描述：
 * 作者：梁帆
 * 时间：2018/5/22 0022
 * 版权：
 */

public class BaseFragment extends Fragment {

    private RequestManager mImgLoader;
    private LayoutInflater mLayoutInflater;
    private LoadingHandler _loadingHandler;
    protected Context mContext;
    private boolean detached = false;
    FrameLayout rootView;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("===", "liangfan....oncreate");
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        Log.e("===", "liangfan....onCreateView");
        this.mLayoutInflater = inflater;
        rootView = (FrameLayout) inflater.inflate(R.layout.fragment_base, null);
        //添加子类 内容区域
        if (createContentView() != null)
            rootView.addView(createContentView());
        return rootView;
    }

    /**给子类实现的内容区域*/
    protected View createContentView() {
        return null;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // 在onAttached()中执行修改detach属性
        mContext = context;
        detached = false;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        _loadingHandler = LoadingHandler.getInstance(getActivity());
        Log.e("===", "liangfan....onActivityCreated");
    }

    public void showLoading() {
        _loadingHandler.showLoading();
    }

    protected View inflateContentView(int resId) {
        return getLayoutInflater().inflate(resId, null, false);
    }

    public void hideLoading() {
        if(_loadingHandler!=null)
            _loadingHandler.hideLoading();
    }



    /***
     * 从网络中加载数据
     *
     * @param viewId   view的id
     * @param imageUrl 图片地址
     */
    protected void setImageFromNet(int viewId, String imageUrl) {
        setImageFromNet(viewId, imageUrl, 0);
    }

    /***
     * 从网络中加载数据
     *
     * @param viewId      view的id
     * @param imageUrl    图片地址
     * @param placeholder 图片地址为空时的资源
     */
    protected void setImageFromNet(int viewId, String imageUrl, int placeholder) {
        ImageView imageView = rootView.findViewById(viewId);
        setImageFromNet(imageView, imageUrl, placeholder);
    }

    /***
     * 从网络中加载数据
     *
     * @param imageView imageView
     * @param imageUrl  图片地址
     */
    protected void setImageFromNet(ImageView imageView, String imageUrl) {
        setImageFromNet(imageView, imageUrl, 0);
    }

    /***
     * 从网络中加载数据
     *
     * @param imageView   imageView
     * @param imageUrl    图片地址
     * @param placeholder 图片地址为空时的资源
     */
    protected void setImageFromNet(ImageView imageView, String imageUrl, int placeholder) {
        ImageLoader.loadImage(getImgLoader(), imageView, imageUrl, placeholder);
    }

    /**
     * 获取一个图片加载管理器
     *
     * @return RequestManager
     */
    public synchronized RequestManager getImgLoader() {
        if (mImgLoader == null)
            mImgLoader = Glide.with(this);
        return mImgLoader;
    }

    @Override
    public void onDetach() {
        super.onDetach();

        mContext = null;

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }




    /**
     * 这个方法让外部能够访问detached属性
     */
    public boolean isFragmentDetached() {
        return detached;
    }

    protected void replaceFragment(int frameLayoutId, Fragment fragment) {
        // 如果已经detached了，则不再执行任何操作
        if (isFragmentDetached()) {
            return;
        }
        if (getActivity() != null && !getActivity().isFinishing()) {
            if (fragment != null) {
                FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                transaction.replace(frameLayoutId, fragment);
                transaction.commitAllowingStateLoss();
            }
        }

    }


    /**
     * 界面跳转
     *
     * @param cls 目标Activity
     */
    protected void readyGo(Class<?> cls) {
        readyGo(cls, null);
    }

    /**
     * 跳转界面，传参
     *
     * @param cls    目标Activity
     * @param bundle 数据
     */
    public void readyGo(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(getActivity(), cls);
        if (null != bundle)
            intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 跳转界面并关闭当前界面
     *
     * @param cls 目标Activity
     */
    protected void readyGoThenKill(Class<?> cls) {
        readyGoThenKill(cls, null);
    }

    /**
     * @param cls    目标Activity
     * @param bundle 数据
     */
    protected void readyGoThenKill(Class<?> cls, Bundle bundle) {
        readyGo(cls, bundle);
        getActivity().finish();
    }

    /**
     * startActivityForResult
     *
     * @param cls         目标Activity
     * @param requestCode 发送判断值
     */
    protected void readyGoForResult(Class<?> cls, int requestCode) {
        Intent intent = new Intent(getActivity(), cls);
        startActivityForResult(intent, requestCode);
    }

    /**
     * startActivityForResult with bundle
     *
     * @param cls         目标Activity
     * @param requestCode 发送判断值
     * @param bundle      数据
     */
    protected void readyGoForResult(Class<?> cls, int requestCode, Bundle bundle) {
        Intent intent = new Intent(getActivity(), cls);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }


}
